﻿using MTQ.BLL;
using MTQ.IBLL;
using MTQ.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MTQ.Common;
using Newtonsoft.Json.Linq;

namespace MTQ.Web.Controllers
{
    public class BaseUserController : BaseController
    {
        private IBase_UserInfoService iBase_userinfoService = new Base_UserInfoService();

        //
        // GET: /BaseUser/
        [AccountAuth(Roles = "Base_UserInfo_Index")]
        public ActionResult Index()
        {
            ViewBag.User_UserName = Base_LocalService.GetWord("User_UserName", CultureInfoName);

            return View();
        }


        [AccountAuth(Roles = "Base_UserInfo_Index")]
        public ActionResult Search()
        {
            Base_UserInfoQuery userinfoQuery = new Base_UserInfoQuery();

            userinfoQuery.Searchkey = GetRequestQueryString("keyword");
            userinfoQuery.User_RealName = GetRequestQueryString("username");
            userinfoQuery.Base_UserInfoAvailable = GetRequestQueryString("available");

            ServertLayuiTable<Base_UserInfo> servertBootStrapTable = new ServertLayuiTable<Base_UserInfo>();
            GetSearchData(ref servertBootStrapTable, true);
            //var servertBootStrapTable = iBase_userinfoService.LoadLayuiSearchData(userinfoQuery, Request);
            //ServertLayuiTable<TestCode3> servertBootStrapTable = new ServertLayuiTable<TestCode3>();
            //servertBootStrapTable.code = 0;
            //servertBootStrapTable.count = 0;
            //servertBootStrapTable.data = new List<TestCode3>();

            //TestCode3Controller testCode3Controller = new TestCode3Controller();
            //servertBootStrapTable=testCode3Controller.GetSearchData(true);

            return Json(servertBootStrapTable, JsonRequestBehavior.AllowGet);
        }


        public ActionResult Export()
        {
            ServertLayuiTable<Base_UserInfo> servertBootStrapTable = new ServertLayuiTable<Base_UserInfo>();
            GetSearchData(ref servertBootStrapTable, false);

            string[,] template = new string[,] {
                {"账户","User_UserName", "{0}" },
                {"姓名","User_RealName", "{0}" },
                {"邮件","User_Email", "{0}" },
                { "邮件", "User_Email", "{0}" },
                { "性别", "User_Sex", "{0}" },
                { "手机", "User_PhoneNumber", "{0}" },
                { "单位名称","User_CompanyName", "{0}" },
                { "部门","User_DepartmentName", "{0}" },
                { "职位", "Organization_Name", "{0}" },
                { "角色", "UserRoleRemark", "{0}" },
                {"创建人","CreateUserName", "{0}" },
                {"状态","User_Available_Text", "{0}" },
            };



            ExportHelper<Base_UserInfo> exportHelper = new ExportHelper<Base_UserInfo>();
            System.IO.MemoryStream output = exportHelper.ExportWriter(servertBootStrapTable.data, template);
            return File(output, "text/comma-separated-values", "用户列表" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv");
        }


        public void GetSearchData(ref ServertLayuiTable<Base_UserInfo> servertBootStrapTable, bool page)
        {
            Base_UserInfoQuery userinfoQuery = new Base_UserInfoQuery();
            userinfoQuery.Searchkey = GetRequestQueryString("keyword");
            userinfoQuery.User_RealName = GetRequestQueryString("username");
            userinfoQuery.Base_UserInfoAvailable = GetRequestQueryString("available");

            if (page)
            {
                servertBootStrapTable = iBase_userinfoService.LoadLayuiSearchData(userinfoQuery, Request);
            }
            else
            {
                IQueryable<Base_UserInfo> iqMachine_Running = iBase_userinfoService.GetIQueryable(userinfoQuery);
                servertBootStrapTable.data = iqMachine_Running.ToList();
                servertBootStrapTable.count = iqMachine_Running.Count();
            }

            List<Base_Organization> listOrganization = new Base_OrganizationService().LoadEntities(x => true).ToList();
            List<Base_Department> listDepartment = new Base_DepartmentService().LoadEntities(x => true).ToList();

            servertBootStrapTable.data.ForEach(x =>
            {
                if (x.User_Available == "Y")
                {
                    x.User_Available_Text = "正常";
                }
                else if (x.User_Available == "N")
                {
                    x.User_Available_Text = "禁用";
                }
                else
                {
                    x.User_Available_Text = x.User_Available;
                }

                if (x.Organization_Id != null)
                {
                    Base_Organization base_Organization = listOrganization.Where(y => y.Organization_Id == x.Organization_Id).FirstOrDefault();
                    if (base_Organization != null)
                    {
                        x.Organization_Name = base_Organization.Organization_Name;
                    }
                }
                if (x.Department_Id != null)
                {
                    Base_Department base_Department = listDepartment.Where(y => y.Department_Id == x.Department_Id).FirstOrDefault();
                    if (base_Department != null)
                    {
                        x.User_DepartmentName = base_Department.Department_Name;

                        Guid? parentdepartid = base_Department.Department_ParentId;
                        while (true)
                        {
                            Base_Department company = listDepartment.Where(y => y.Department_Id == parentdepartid).FirstOrDefault();
                            if (company == null)
                            {
                                break;
                            }
                            if (company.Department_ParentId == new Guid("00000000-0000-0000-0000-000000000000"))
                            {
                                x.User_CompanyName = company.Department_Name;
                                break;
                            }
                            parentdepartid = company.Department_ParentId;
                        }
                    }
                }

            });
        }


        //          
        // GET: /Base_UserInfo/Create          
        [AccountAuth(Roles = "Base_UserInfo_Create")]
        public ActionResult Create()
        {
            Base_UserInfo Base_userinfo = new Base_UserInfo();
            Base_userinfo.User_Id = System.Guid.NewGuid();

            return View(Base_userinfo);
        }

        //          
        // POST: /Base_UserInfo/Create          
        [HttpPost]
        [AccountAuth(Roles = "Base_UserInfo_Create")]
        public ActionResult Create(Base_UserInfo Base_userinfo)
        {
            ModelMessage listMsg = new ModelMessage();
            if (ModelState.IsValid)
            {
                Base_userinfo.User_Id = System.Guid.NewGuid();
                Base_userinfo.CreateDateTime = System.DateTime.Now;
                Base_userinfo.User_Id = System.Guid.NewGuid();
                Base_userinfo.CreateUserId = CurrentUserInfo.User_Id;
                Base_userinfo.CreateUserName = CurrentUserInfo.User_UserName;
                Base_userinfo.User_Status = 1;
                Base_userinfo.User_Code = Base_userinfo.User_RealName;
                Base_userinfo.User_Password = MD5Cryptography.MD5Encrypt(Base_userinfo.User_Password);
                //Base_userinfo.Organization_Id = CurrentUserInfo.Organization_Id;
                //Base_userinfo.Department_Id = CurrentUserInfo.Department_Id;
                Base_userinfo.User_Available = "Y";


                if (!string.IsNullOrEmpty(Base_userinfo.Role_Id))
                {
                    Guid guid = new Guid(Base_userinfo.Role_Id);
                    Base_UserRole userrole = new Base_UserRole() { UserRole_Id = System.Guid.NewGuid(), Base_UserId = Base_userinfo.User_Id, Base_RoleId = guid };

                    Base_UserRoleService urs = new Base_UserRoleService();
                    urs.AddEntity(userrole);

                    Base_RoleService roles = new Base_RoleService();
                    Base_userinfo.UserRoleRemark = roles.LoadEntities(x => x.Role_Id == guid).First().Role_Name;
                }

                var result = iBase_userinfoService.AddEntity(Base_userinfo);
                listMsg = new ModelMessage("ChangeResult", "m001", result != null ? "保存成功" : "保存失败");
            }
            return Json(listMsg);
        }

        // POST: /Base_UserInfo/Create                                                    
        [AccountAuth(Roles = "Base_UserInfo_Edit")]
        public ActionResult Edit(Guid? primarykey)
        {
            Base_UserInfo Base_userinfo = iBase_userinfoService.LoadEntities(x => x.User_Id == primarykey).FirstOrDefault();
            if (Base_userinfo == null)
            {
                return HttpNotFound();
            }
            Base_UserRole userrole = new Base_UserRoleService().LoadEntities(x => x.Base_UserId == Base_userinfo.User_Id).FirstOrDefault();
            if (userrole != null)
            {
                Base_userinfo.Role_Id = userrole.Base_RoleId.ToString();
            }

            return View(Base_userinfo);
        }

        [HttpPost]
        [AccountAuth(Roles = "Base_UserInfo_Edit")]
        public ActionResult Edit(Base_UserInfo userinfo)
        {
            ModelMessage listMsg = new ModelMessage();
            if (ModelState.IsValid)
            {
                try
                {
                    Base_UserInfo bu = iBase_userinfoService.LoadEntities(x => x.User_Id == userinfo.User_Id).First();
                    bu.User_UserName = userinfo.User_UserName;
                    bu.User_Email = userinfo.User_Email;
                    //bu.User_Available = Buserinfo.User_Available;
                    bu.User_Sex = userinfo.User_Sex;
                    bu.User_RealName = userinfo.User_RealName;
                    bu.User_Remark = userinfo.User_Remark;
                    bu.Organization_Id = userinfo.Organization_Id;
                    bu.Department_Id = userinfo.Department_Id;
                    bu.User_PhoneNumber = userinfo.User_PhoneNumber;
                    Base_UserRoleService urs = new Base_UserRoleService();
                    Base_RoleService roles = new Base_RoleService();
                    Base_UserRole userrole = urs.LoadEntities(x => x.Base_UserId == userinfo.User_Id).FirstOrDefault();
                    if (userrole != null)
                    {
                        if (!string.IsNullOrEmpty(userinfo.Role_Id))
                        {
                            Guid guid = new Guid(userinfo.Role_Id);
                            userrole.Base_RoleId = guid;
                            urs.UpdateEntity(userrole);

                            bu.UserRoleRemark = roles.LoadEntities(x => x.Role_Id == guid).First().Role_Name;
                        }
                        else
                        {
                            urs.DeleteEntity(userrole);
                            bu.UserRoleRemark = "";
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(userinfo.Role_Id))
                        {
                            Guid guid = new Guid(userinfo.Role_Id);
                            userrole = new Base_UserRole() { UserRole_Id = System.Guid.NewGuid(), Base_UserId = userinfo.User_Id, Base_RoleId = guid };
                            urs.AddEntity(userrole);
                            bu.UserRoleRemark = roles.LoadEntities(x => x.Role_Id == guid).First().Role_Name;
                        }

                    }




                    bool result = iBase_userinfoService.UpdateEntity(bu);




                    listMsg = new ModelMessage("ChangeResult", "m001", result ? "保存成功" : "保存失败");
                }
                catch (Exception e)
                {
                    listMsg = new ModelMessage("ChangeResult", "m002", "保存失败");
                }
            }
            return Json(listMsg);

        }

        [HttpPost]
        [AccountAuth(Roles = "Base_UserInfo_Edit")]
        public ActionResult ActivateSwich(string Ids, string activate = "N")
        {
            ModelMessage modelMessage = new ModelMessage();

            if (OperatorAvailable(Ids, activate))
            {
                modelMessage.Code = "m001";
                modelMessage.Message = "修改成功";
            }
            else
            {
                modelMessage.Code = "m002";
                modelMessage.Message = "修改失败";
            }
            return Json(modelMessage, JsonRequestBehavior.AllowGet);
        }

        private bool OperatorAvailable(string primarykeys, string available)
        {
            List<Guid> listBase_UserInfoGUID = primarykeys.Split(',').ToListGuid();
            List<Base_UserInfo> listBase_UserInfo = iBase_userinfoService.LoadEntities(x => listBase_UserInfoGUID.Contains(x.User_Id)).ToList();
            foreach (var item in listBase_UserInfo)
            {
                item.User_Available = available;
            }
            int updaterow = iBase_userinfoService.UpdateEntity();
            if (updaterow == 0)
            {
                return false;
            }
            return true;
        }


        [HttpPost]
        [AccountAuth(Roles = "Base_UserInfo_Edit")]
        public ActionResult EditPassword()
        {
            ModelMessage listMsg = new ModelMessage();
            string old_password = GetRequestQueryString("old_password");
            string new_password = GetRequestQueryString("new_password");
            string again_password = GetRequestQueryString("again_password");
            if (new_password != again_password)
            {
                listMsg = new ModelMessage("ChangeResult", "m002", "保存失败,密码不一致");
                return Json(listMsg);
            }
            try
            {
                Base_UserInfo bu = iBase_userinfoService.LoadEntities(x => x.User_Id == CurrentUserInfo.User_Id).First();

                if (bu.User_Password != MD5Cryptography.MD5Encrypt(old_password))
                {
                    listMsg = new ModelMessage("ChangeResult", "m002", "保存失败,原密码不正确");
                }
                else
                {
                    bu.User_Password = MD5Cryptography.MD5Encrypt(again_password);

                    bool result = iBase_userinfoService.UpdateEntity(bu);
                    listMsg = new ModelMessage("ChangeResult", result ? "m001" : "m002", result ? "保存成功" : "保存失败");
                }


            }
            catch (Exception e)
            {
                listMsg = new ModelMessage("ChangeResult", "m002", "保存失败");
            }

            return Json(listMsg);

        }

    }
}
